const Joi = require("joi");
const crypto = require("../utils/crypto");
module.exports = class MeritController extends colpu.Controller {
  /**
   * @api {get} /api/merit/today_log 获得用户元气数据
   * @apiDescription 今日元气统计
   * @apiGroup  用户功德日志接口
   * @apiVersion 1.0.0
   * @apiParam {Number} [today_count]
   * @apiParam {Number} [total_count]
   * @apiParam {String} [province]
   * @apiParam {String} [uid] required
   *
   * @apiSuccess {Number} status 状态码
   * @apiSuccess {String} message 消息
   * @apiSuccess {Object} data 返回结果
   * @apiSuccessExample {json} Success-Response:
   * HTTP/1.1 200 OK
      {
        "data": {
          ...
        },
        "status": 0,
        "message": "ok"
      }
  */
  async getTodayLog(ctx) {
    await ctx.validateAsync({
      query: {
        uid: Joi.string().required(),
        type: Joi.string().required(),
      },
      status: 10001,
    });
    const { type, uid } = ctx.query;
    const res = await this.service.merit.getTodayLog({ type, uid });
    ctx.respond(res);
  }

  async getTodayAllLog(ctx) {
    await ctx.validateAsync({
      query: {
        uid: Joi.string().required(),
      },
      status: 10001,
    });
    const { uid } = ctx.query;
    const res = await Promise.all([
      this.service.merit.getTodayLog({ type: "woodenfish", uid }), // 木鱼
      this.service.merit.getTodayLog({ type: "beads", uid }), // 佛珠
      this.service.merit.getTodayLog({ type: "incense", uid }), // 烧香
      this.service.merit.getTodayAllLog(uid), // 总数据
    ]);
    console.log("md5==>", crypto.md5(JSON.stringify(res)), JSON.stringify(res));

    // 强制阅览器不缓存
    ctx.cacheControl = { noCache: true };
    ctx.respond(res);
  }

  /**
   * @api {put} /api/merit/today_log 功德统计入库
   * @apiDescription 今日元气统计
   * @apiGroup  用户功德日志接口
   * @apiVersion 1.0.0
   * @apiParam {Number} [today_count]
   * @apiParam {Number} [total_count]
   * @apiParam {String} [province]
   * @apiParam {String} [uid] required
   *
   * @apiSuccess {Number} status 状态码
   * @apiSuccess {String} message 消息
   * @apiSuccess {Object} data 返回结果
   * @apiSuccessExample {json} Success-Response:
   * HTTP/1.1 200 OK
      {
        "data": {
          ...
        },
        "status": 0,
        "message": "ok"
      }
  */
  async putTodayLog(ctx) {
    let body = ctx.request.body;
    let validate = {
      type: Joi.string().required(),
      uid: Joi.string().required(),
      today_count: Joi.number().required(),
      today_gather_count: Joi.number().required(),
      province: Joi.string().allow(null, ""),
      incence_count: Joi.number().default(0),
      background: Joi.string().allow(null, ""),
    };
    const { version } = ctx.query;
    if (version >= "1.0.4") {
      validate.mantra_id = Joi.number().required();
    }
    if (Array.isArray(body)) {
      validate = [validate];
    }
    await ctx.validateAsync({
      body: validate,
      status: 10001,
    });
    let res = "";
    if (Array.isArray(body)) {
      const prmList = [];
      body.forEach((item) => {
        prmList.push(this.service.merit.putTodayLog(item));
      });
      res = await Promise.all(prmList);
    } else {
      res = await this.service.merit.putTodayLog(body);
    }
    ctx.respond(res);
  }

  async totalLogByType(ctx) {
    await ctx.validateAsync({
      query: {
        uid: Joi.string().required(),
        type: Joi.string(),
      },
      status: 10001,
    });
    const res = await this.service.merit.totalLogByType(ctx.query);
    ctx.respond(res);
  }

  async getDonateLog(ctx) {
    await ctx.validateAsync({
      query: {
        uid: Joi.string().required(),
      },
      status: 10001,
    });
    const res = await this.service.merit.getDonateLog(ctx.query);
    ctx.respond(res);
  }

  async putDonateLog(ctx) {
    await ctx.validateAsync({
      body: {
        uid: Joi.string().required(),
        count: Joi.number().required(),
        province: Joi.string().required(),
      },
      status: 10001,
    });
    const { count, province, uid } = ctx.request.body;
    let { donate_count } = await this.service.merit.getDonateLog({
      uid,
    });
    const { total_count } = await this.service.merit.totalLogByType({ uid });
    const leave_total_count = total_count - donate_count;
    if (leave_total_count < count) {
      ctx.respond(null, -1, "当前元气数量不够。");
    } else {
      await this.service.merit.putDonateLog({
        donate_count: count,
        province,
        uid,
      });
      ctx.respond(leave_total_count, 0, `捐献${count}元气成功！`);
    }
  }

  /**
   * @api {put} /api/merit/save 功德统计入库
   * @apiDescription 功德统计
   * @apiGroup  用户功德日志接口
   * @apiVersion 1.0.0
   * @apiParam {Number} [today_count]
   * @apiParam {Number} [total_count]
   * @apiParam {String} [province]
   * @apiParam {String} [uid] required
   *
   * @apiSuccess {Number} status 状态码
   * @apiSuccess {String} message 消息
   * @apiSuccess {Object} data 返回结果
   * @apiSuccessExample {json} Success-Response:
   * HTTP/1.1 200 OK
      {
        "data": {
          ...
        },
        "status": 0,
        "message": "ok"
      }
  */
  // 修改数据库后，做保留接口兼容
  async saveCount(ctx) {
    await ctx.validateAsync({
      body: {
        today_count: Joi.number().required(),
        province: Joi.string().allow(null, ""),
        uid: Joi.string().required(),
      },
      status: 10001,
    });
    const body = ctx.request.body;
    body.type = "woodenfish";
    body.incence_count = 0;
    body.today_gather_count = max(10, Math.floor(body.today_count / 10));
    await this.service.merit.todayLog(body);
    ctx.respond(null);
  }

  async getCount(ctx) {
    await ctx.validateAsync({
      query: {
        uid: Joi.string().required(),
      },
      status: 10001,
    });
    const data = await this.service.merit.getCount(ctx.request.query);
    ctx.respond(data);
  }

  async donate(ctx) {
    await ctx.validateAsync({
      body: {
        uid: Joi.string().required(),
        count: Joi.number().required(),
        province: Joi.string(),
      },
      status: 10001,
    });
    const { count, province, uid } = ctx.request.body;
    let { total_count, donate_count } = await this.service.merit.getCount({
      uid,
    });
    donate_count = parseInt(donate_count, 10);
    const leaveCount = parseInt(total_count, 10) - donate_count;
    if (leaveCount < count) {
      ctx.respond(null, -1, "当前功德数量不够。");
    } else {
      donate_count += count;
      await this.service.merit.putDonateLog({
        donate_count: count,
        province,
        uid,
      });

      ctx.respond({ total_count, donate_count }, 0, `捐献${count}功德成功！`);
    }
  }

  async list(ctx) {
    const res = await this.service.merit.list();
    ctx.respond(res);
  }

  async province(ctx) {
    await ctx.validateAsync({
      query: {
        province: Joi.string().min(2).required(),
      },
      status: 10001,
    });
    const res = await this.service.merit.province(ctx.query.province);
    ctx.respond(res);
  }
};
